package com.ruoyi.factory.taxShare.common;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

public class AesCryptoUtil {

    // 硬编码的密钥
    private static final String HARDCODED_KEY = "5hUbo4zNIisGZMtK"; // 16字节

    // 固定IV（可选）
    private static final String FIXED_IV = "1234567890123456"; // 16字节

    /**
     * 加密 - 使用固定IV
     */
    public static String encrypt(String data) throws Exception {
        return encrypt(data, HARDCODED_KEY, FIXED_IV);
    }

    /**
     * 解密 - 使用固定IV
     */
    public static String decrypt(String encryptedData) throws Exception {
        return decrypt(encryptedData, HARDCODED_KEY, FIXED_IV);
    }

    /**
     * 加密 - 从密钥派生IV
     */
    public static String encryptWithDerivedIV(String data) throws Exception {
        String derivedIV = deriveIVFromKey(HARDCODED_KEY);
        return encrypt(data, HARDCODED_KEY, derivedIV);
    }

    /**
     * 解密 - 从密钥派生IV
     */
    public static String decryptWithDerivedIV(String encryptedData) throws Exception {
        String derivedIV = deriveIVFromKey(HARDCODED_KEY);
        return decrypt(encryptedData, HARDCODED_KEY, derivedIV);
    }

    /**
     * 从密钥派生IV
     */
    private static String deriveIVFromKey(String key) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(key.getBytes("UTF-8"));
        // 取前16字节作为IV
        byte[] ivBytes = new byte[16];
        System.arraycopy(hash, 0, ivBytes, 0, 16);
        return new String(ivBytes, "UTF-8");
    }

    // 原有的加密解密方法
    private static String encrypt(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.encodeBase64String(encrypted);
    }

    private static String decrypt(String encryptedData, String key, String iv) throws Exception {
        byte[] encryptedBytes = Base64.decodeBase64(encryptedData);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] original = cipher.doFinal(encryptedBytes);
        return new String(original, "UTF-8");
    }
}